package cn.smbms.web;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.mysql.jdbc.StringUtils;

import cn.smbms.pojo.User;
import cn.smbms.service.UserService;


/**
 * @author W
 *
 */
@Controller
public class UserController {
	@Autowired
	private UserService userService;
	
	@RequestMapping(value="deleteuid",method=RequestMethod.GET)
	public String deleteuid(@RequestParam("uid")Integer uid){
		int i = userService.finddeleteUid(uid);
		return "redirect:/getUsers";
	}
	@RequestMapping(value="queryuid",method=RequestMethod.GET)
	public String queryuid(@RequestParam("uid")Integer uid,HttpServletRequest request){
		User user = userService.findqueryUid(uid);
		request.setAttribute("user", user);
		return "userview";
	}
	@RequestMapping(value="login",method=RequestMethod.GET)
	public String login(){
		return "login";
	}
	
	@RequestMapping(value="login",method=RequestMethod.POST)
	public String   doLogin(User user){
		
		User loginUser=userService.tofindByUsercode(user);
		if(null!=loginUser){
			return "frame";
		}else{
			return "login";
		}
	}
	//进入注册页面
	/*@RequestMapping(value="/register",method=RequestMethod.GET)
	  public String register(){
		return "register";
	}*/
	/*//传递一个参数到后台
	@RequestMapping(value="/register/{iString}",method=RequestMethod.GET)
	public String register(){
	//Spring表单标签   
	public String register(@ModelAttribute("user") User user,@PathVariable String iString){
		return "register";
	}*/
	@RequestMapping(value="/register",method=RequestMethod.GET)
	//Spring表单标签
	public String register(@ModelAttribute("user") User user){
		return "register";
	}
	
	@RequestMapping(value="/register",method=RequestMethod.POST)
	//数据校验     上传
	public String doregister( User user,BindingResult bindingResult,@RequestParam("imgName") MultipartFile attach,HttpServletRequest request){
		//图片路径
		String idPicPath=null;
		if(bindingResult.hasErrors()){
			return "register";
		}
		//判断不为空
		if(!attach.isEmpty()){
			//得到真实路径
			String path=request.getSession().getServletContext().getRealPath("fileUpLoad");
			System.out.println(path);
			//得到源文件名称123.png
			String oldFileName=attach.getOriginalFilename();
			//得到源文件后缀
			String prefix=FilenameUtils.getExtension(oldFileName);
			//设置上传文件大小5000为1K
			int fileSize=500000;
			if(attach.getSize()>fileSize){
				//不符合大小
				request.setAttribute("uploadFileError","请注意上传文件大小，不要超过500kb");
			}else{
				//符合之后
				//进行后缀名判断 jpg  png  gif
				if(prefix.equalsIgnoreCase("jpg")||prefix.equalsIgnoreCase("png")||prefix.equalsIgnoreCase("gif")){
					//将要保存的文件名  当前时间秒数+随机数+_myImg.+后缀名3456789_myImg.png
					String fileName=System.currentTimeMillis()+RandomUtils.nextInt(100000)+"_myImg."+prefix;
					//目标文件类 io包
					File targetFile=new File(path,fileName);
					if(!targetFile.exists()){
						targetFile.mkdirs();
					}
					//把文件中的内容输出
					try {
						attach.transferTo(targetFile);
						//没问题开始保存  斜杠兼容    例： /fileUpLoad/92347347847_myImg.jpg
						idPicPath="fileUpLoad"+File.separator+fileName;
					} catch (IllegalStateException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}else{
					System.out.println("文件格式不正确！");
				}
			}
		}
		user.setImgPath(idPicPath);
		int result=userService.toaddUser(user);//1
		if(result>0){
			//登陆
			return "login";
		}else{
			//注册
			return "register";
		}
	}
	//判断userCode是否存在
	@RequestMapping("/userCodeExit.html")
	//返回到响应体中
	@ResponseBody
	public Object userCodeIsExit(@RequestParam("userCode") String userCode){
		HashMap<String ,String> map=new HashMap<String ,String>();
		if(!StringUtils.isNullOrEmpty(userCode)){
			map.put("userCode2", "用户名不能为空，不能为NUll");
		}else{
			User queryUser=userService.tofindUserByUserCode(userCode);
			if(queryUser==null){
				map.put("userCode2", "可以使用此账号");
			}else{
				//账号已经注册过
				map.put("userCode2", "账号已经存在，不能使用");
			}
			
		}
		//JSON字符串形式
		return JSONArray.toJSONString(map);
	}
	@RequestMapping("/getUsers")
	public String getAllUser(HttpServletRequest request){
		//得到所有用户信息
		List<User> userList=userService.tofindListUser();//2
		//控制台输出所有用户信息
		for (User user : userList) {
			System.out.println(user.getUserName());
		}
		ModelAndView modelAndView=new ModelAndView();
		modelAndView.addObject("userList",userList);
		request.setAttribute("userList",userList);
		return "userList";
	}
	
	//JSON乱码   406吧 .html去掉,单个json乱码处理
	//@RequestMapping(value="/getUserByUserId",produces={"application/json;charset=UTF-8"})
	@RequestMapping(value="/getUserByUserId")
	@ResponseBody
	public Object getId(@RequestParam("userId") Integer id,HttpServletResponse response){
		User user=userService.tofingUserByUserId(id);//3
		String userString=JSONArray.toJSONString(user);
		//response.setContentType("application/json;charset=UTF-8");?
		return user;
	}
	@RequestMapping("/updateInfo")
	public String updateUsers(User user){
		int count=userService.toupdateUserByid(user);
		System.out.println("删除用户信息影响行数"+count);
		return "usermodify";
	}
}
